convert hex to dec or dec to hex conversion

chris (2004-12-16 16:40:53)
75344 views
1 replies
Well here's a dead simple way of converting betwen hex and dec in perl..
#!/usr/bin/perl
$foo = 10;

$hexval = sprintf("%x", $foo);
$decval =  hex($hexval);

print "\n$foo in hex is $hexval and in dec is $decvaln";

# end
Cut and paste the above code into a new file, save it as hexdec.pl or dechex.pl or whatever and ensure that you have execute permissions. The script creates a variable, $foo with a value of your choice, (in this case 10). It will then print out it's value in hexadecimal and in decimal.

Christo
comment
jeff
2009-11-12 21:11:16

correction

you have a typo. you forgot a \n :)

here's an improved version for fun

#!/usr/bin/perl -w
# hexadec.pl

print "hexa converter\n\nPlease enter a hexadecimal: ";
$foo = <STDIN>;
$hexval = sprintf("%x", $foo);
$decval = hex($hexval);
print "\n$foo in hex is $hexval and in dec is $decval\n";
reply iconedit reply